package com.album.utils;

 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.album.R;
import com.album.activity.MessageDialog;
import com.album.common.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; 
/**
 * 
 * @author Rome
 * 2011.6.29
 * 普通事务处理类
 */
public class CommonUtil {
	private static Gson gson = new Gson();
	public static int width;
    public static int height;
    public static String friendname;
    public static String friendnick;
    
    
    
    private static String TAG = "CommonUtil";
    /**
     * 获取手机IMSI
     * @param c
     * @return
     */
	public static String getIMSI(Context c){
		String IMSI =null;
		try {
			
			TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);//      
	        IMSI = tm.getSubscriberId();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return IMSI;
	}
	/**
	 * 获取图片地址
	 * @param username
	 * @param headname
	 * @return
	 */
	public static String getHeadImage(String username,String headname){
		if(!"".equals(headname))
			headname = headname.substring(headname.lastIndexOf("/")+1);
		String headUrl = username+"/"+headname;
		return headUrl;
	}
	public static String getUsername(String username){
		if(!"".equals(username))
			username = username.substring(0,username.lastIndexOf("@"));
		return username;
	}
	
	/**
	 * @param jsonString
	 *            rome 2011.6.27 json 解析处理
	 * @return List<sellingBean>
	 */
    
    public static List<Object> getGsonList(String rspString){
    	 Gson gson = new Gson();
    	List<Object> list = null;
    	try {
    		list = gson.fromJson(rspString, new TypeToken<List<Object>>() {}.getType());
    		
		} catch (Exception e) {
			return null;
		}
		return list;
    }
 // 缩小放大图片
	public static Bitmap createImage(Bitmap src, int destWidth, int destHeigth, boolean isScale) {
		Bitmap ret = null;
		if (isScale == true) {// 等比例
			int w = src.getWidth();
			int h = src.getHeight();

			float scaleWidth = (float) destWidth / w;
			float scaleHeight = (float) destHeigth / h;
			float scale = Math.max(scaleWidth, scaleHeight);
			Matrix m = new Matrix();
			m.postScale(scale, scale);
			ret = Bitmap.createBitmap(src, 0, 0, w, h, m, true);
			m.reset();
			m = null;
//			imageScale = scale;
		} else {
			ret = Bitmap.createScaledBitmap(src, destWidth, destHeigth, true);
		}

		return ret;
	}
	//将Drawable转化为Bitmap     
    public static Bitmap drawableToBitmap(Drawable drawable){     
           int width = drawable.getIntrinsicWidth();     
           int height = drawable.getIntrinsicHeight();     
           Bitmap bitmap = Bitmap.createBitmap(width, height,     
                   drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888     
                           : Bitmap.Config.RGB_565);     
           Canvas canvas = new Canvas(bitmap);     
           drawable.setBounds(0,0,width,height);     
           drawable.draw(canvas);     
           return bitmap;     
                
       }     
	/**
	 * 
	 @author 吴新
	 * @createTime：2011-7-11 上午11:27:41
	 * @packageName:VipShopWidgetTest_712
	 * @com.vip.util.JsonParseUtils.java
	 */
	public static List<Object> parseFromJson(String jsonstring) {
		List<Object> list = null;
		try {
			MyLog.debug(CommonUtil.class, jsonstring);
			list = gson.fromJson(jsonstring, new TypeToken<List<Object>>() {
			}.getType());
		} catch (Exception e) {
			return null;
		}
		return list;
	}
	/**
	 * 获取设备唯一标识
	 */
	public static String getDeviceID(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	/**
	 * 判断网络类型
	 * @return
	 */
	public static boolean isWap() {
		String proxyHost = android.net.Proxy.getDefaultHost();
		if (proxyHost != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检测SDcard是否存在
	 * 
	 * @return true:存在、false:不存在
	 */
	public static boolean checkSDcard() {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否插入了sim卡
	 */
	public static boolean hasSimCard(Context context) {
		TelephonyManager manager = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		boolean flag = false;
		switch (manager.getSimState()) {
		case TelephonyManager.SIM_STATE_ABSENT:
		case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
		case TelephonyManager.SIM_STATE_PIN_REQUIRED:
		case TelephonyManager.SIM_STATE_PUK_REQUIRED:
		case TelephonyManager.SIM_STATE_UNKNOWN:
			flag = false;
			break;
		case TelephonyManager.SIM_STATE_READY:
			flag = true;
			break;
		}
		return flag;
	}

	/**
	 * 删除文件或文件夹
	 * 
	 * @return
	 */
	public static void deleteFile(String fileName) {
		File f = new File(fileName);
		if (f.exists()) {
			if (f.isFile()) {
				f.delete();
			} else if (f.isDirectory()) {
				String[] files = f.list();
				int len = files.length;
				for (int i = 0; i < len; i++) {
					deleteFile(files[i]);
				}
			}
		}
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean isExists(String fileName) {
		File f = new File(fileName);
		return f.exists();
	}

	/**
	 * 检测网络连接是否可用
	 * 
	 * @param ctx
	 * @return true 可用; false 不可可用
	 */
	public static boolean CheckNetWork(Context ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
			return false;
		}
		NetworkInfo[] netinfo = cm.getAllNetworkInfo();
		if (netinfo == null) {
			return false;
		}
		for (int i = 0; i < netinfo.length; i++) {
			if (netinfo[i].isConnected()) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取当前版本号
	 */
	public static int getVersion(Context context) {
		int nowVersion = 0;
		try {
			nowVersion = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
			Log.d("", "mid--------------versionName" + nowVersion);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			return nowVersion;
		}
	}
	/**
	 * 保存图片
	 * @param bitmapData
	 * @param fileName
	 * @param savePath
	 * @return
	 */
	public static File saveBitmap(byte bitmapData[],String fileName,String savePath) {
//		String fileName = System.currentTimeMillis() + ".jpg";
		//MyLog.info(TAG, "ImagePath:" + savePath);
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File myCaptureFile = new File(savePath + fileName);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			bos.write(bitmapData);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		return myCaptureFile;
	}

	/**
	 * 获取本地sd图片
	 * 
	 * @param fileName
	 * @return
	 */
	public static Bitmap getBitmap(String filePath) {
		Bitmap localBm = BitmapFactory.decodeFile(filePath);
		return localBm;
	}
	/**
	 * sd卡地址
	 * @return
	 */
	public static String getSdCardDir(){
		File sdCardDir = android.os.Environment .getExternalStorageDirectory();
		return  sdCardDir.getPath();
	}
	/*
	 * init图片存储文件夹
	 */
	public static File initFolder(Context context) {
		synchronized (CommonUtil.class) {
			File dirFile  = null;
			try {
				// 获取SDCard目录,2.2的时候为:/mnt/sdcart
				// 2.1的时候为：/sdcard，所以使用静态方法得到路径会好一点。
				try {
					dirFile = new File(getSdCardDir()+Config.public_image);
					if (!dirFile.exists()) {
						dirFile.mkdirs();
					}
					dirFile = new File(getSdCardDir()+Config.private_image);
					if (!dirFile.exists()) {
						dirFile.mkdirs();
					}
					dirFile = new File(getSdCardDir()+Config.share_image);
					if (!dirFile.exists()) {
						dirFile.mkdirs();
					}
				} catch (Exception e) { } 
				
			} catch (Exception e) {
			}
			return dirFile;
		}
	}
	/** 
     * 保存文件 
     * @param bm 
     * @param fileName 
     * @throws IOException 
     */  
    public static File saveFileBitmap(Bitmap bm, String ALBUM_PATH,String fileName){  
        File dirFile = new File(ALBUM_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }  
        File myCaptureFile = new File(ALBUM_PATH + fileName); 
        Log.i("", "save image filepath:"+myCaptureFile);
//        MyLog.debug(TAG, "path:"+myCaptureFile.getPath());
        BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
	        bm.compress(Bitmap.CompressFormat.PNG, 100, bos); 
			bos.close(); 
			bos.flush();
		} catch (FileNotFoundException e) { return null;
    	} catch (IOException e) {return null;}
        return myCaptureFile;
    } 

	
	/**
	 * 把毫秒换算成标准的年月日
	 * @param nCurrentTime
	 * @return
	 */
	public static String getData(int nCurrentTime){
		 //Calendar用于获取指定的时间项（字段）
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(nCurrentTime);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;   //注意：返回的月份是基于0的！
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String data = year + "-" + month + "-" + day;
        return data;
	}
	/**
	 * 两个日期大小比较
	 * @param DATE1
	 * @param DATE2
	 * DATE1 大于 DATE2返回 1 ，小于返回-1，相等返回0
	 * @return
	 */
	
	 public static int compare_date(String DATE1, String DATE2) {
	        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	        int i = 0;
	        try {
	            Date dt1 = df.parse(DATE1);
	            Date dt2 = df.parse(DATE2);
	           i = dt1.compareTo(dt2);
	           System.out.println("test:"+i);
//	            if (dt1.getTime() > dt2.getTime()) {
//	                System.out.println("dt1 在dt2前");
//	                return 1;
//	            } else if (dt1.getTime() < dt2.getTime()) {
//	                System.out.println("dt1在dt2后");
//	                return -1;
//	            } else {
//	                return 0;
//	            }
	        } catch (Exception exception) {
	            exception.printStackTrace();
	        }
	        return i;
	    }
	 /**
	  * 判断文件夹是否为空
	  * true 为空  false 不为空
	  * @param path
	  * @return
	  */
	public static boolean isFileEmpty(String path) {
		Log.i(TAG, "isFileEmpty():"+path);
		try {
			File file = new File(path);
			File[] files = file.listFiles();
			Log.i(TAG, "file.isDirectory():"+file.isDirectory());
			if (file.isDirectory()) {
				if (files.length > 0) {
					Log.i(TAG,"file > 0");
					return false;
			}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	 /**
	  * 获取当前时间
	  * @return
	  */
	 public static String getNowData(){
		 Calendar calendar = Calendar.getInstance();  
	        int year = calendar.get(Calendar.YEAR);  
	        int month = calendar.get(Calendar.MONTH);  
	        int day = calendar.get(Calendar.DAY_OF_MONTH);  
	        int hour = calendar.get(Calendar.HOUR_OF_DAY);  
	        int minute = calendar.get(Calendar.MINUTE);  
	        int second = calendar.get(Calendar.SECOND); 
	        return year+"-"+month+"-"+day;
	 }
	 /**
	  * 图片截圆角
	  * @param bitmap
	  * @return
	  */
	 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {    
		    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),    
		        bitmap.getHeight(), android.graphics.Bitmap.Config.ARGB_8888);    
		    Canvas canvas = new Canvas(output);    
		     
		    final int color = 0xff424242;    
		    final Paint paint = new Paint();    
		    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());    
		    final RectF rectF = new RectF(rect);    
		    final float roundPx = 13f;    
		     
		    paint.setAntiAlias(true);    
		    canvas.drawARGB(0, 0, 0, 0);    
		    paint.setColor(color);    
		    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);    
		     
		    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));    
		    canvas.drawBitmap(bitmap, rect, rect, paint);    
		     
		    return output;    
		  }   

	/**
	 * 
	 * @param imageUrl
	 * @param bm
	 */
	public static void saveImage(String imageUrl, Bitmap bm) {
		String fileName = null;
		if (imageUrl != null && imageUrl.length() != 0) {
			fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
		}
		if (bm != null) {
			//bm = CommonUtil.getRoundedCornerBitmap(bm); //图片截圆角
			saveFileBitmap(bm,CommonUtil.getSdCardDir() + Config.album_image, fileName);
		}
	}
		/**
		 * 下载图片
		 * 
		 * @param c
		 * @param url
		 * @return
		 */
	public synchronized static Bitmap loadBitMap(Context ctx, String url) {
		Log.i(TAG, "loadBitMap():"+url);
		Bitmap bitmap = null;
		try {
			if (CheckNetWork(ctx)) {
				URL myFileUrl = new URL(url);
				HttpURLConnection conn = null;
				if (isWap()) {
					Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,
							new InetSocketAddress("10.0.0.172", 80));
					conn = (HttpURLConnection) myFileUrl.openConnection(proxy);
				} else {
					conn = (HttpURLConnection) myFileUrl.openConnection();
				}
				conn.setDoInput(true);
				conn.connect();
				InputStream is = conn.getInputStream();
				int length = (int) conn.getContentLength();
				Log.i(TAG, "length:" + "111" + length);
				if (length != -1) {
					byte[] imgData = new byte[length];
					byte[] temp = new byte[512];
					int readLen = 0;
					int destPos = 0;
					while ((readLen = is.read(temp)) > 0) {
						System.arraycopy(temp, 0, imgData, destPos, readLen);
						destPos += readLen;
					}
					bitmap = BitmapFactory.decodeByteArray(imgData, 0,
							imgData.length);
//					bitmap = Bitmap.createScaledBitmap(bitmap, 436, 124, true);// 预先缩放，避免实时缩放，可以提高更新率
				}
			}else{
				//MessageDialog.showToast(ctx, false, ctx.getString(R.string.int_error));
			}
		} catch (IOException e) { return null;
		}catch (OutOfMemoryError ex){ return null;}
		return bitmap;
	}
		/**
		 * 缓冲10k
		 */
		public static final int IO_BUFFER_SIZE = 10 * 1024; // 10k

		private static void copy(InputStream in, OutputStream out) throws IOException {
			byte[] b = new byte[IO_BUFFER_SIZE];
			int read;
			while ((read = in.read(b)) != -1)
				out.write(b, 0, read);
		}

		private static final void closeStream(Closeable stream) {
			if (stream != null)
				try {
					stream.close();
				} catch (IOException e) {
				}
		}
		public static boolean isNetWorkActive(Context inContext) {
			boolean isNetWork = false;
			Context context = inContext.getApplicationContext();
			ConnectivityManager connectivity =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
			try {
				if (connectivity != null) {
					NetworkInfo[] info = connectivity.getAllNetworkInfo();
					if (info != null) {
						for (int i = 0; i < info.length; i++) {
							//info[i].getType()==ConnectivityManager.TYPE_WIFI
							if (info[i].isConnected()) {
								MyLog.info(inContext.getClass(), "Active Network Type........................"+ info[i].getTypeName());
								isNetWork = true; break;
							}
						}
					}
				}
			} catch (Exception e) { return false; }
			return isNetWork;
		}
		
		//保存用户信息
		public static void setUserInfo(String userName,String pwd,Context context){
		    SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			Editor edit = ferences.edit();
			edit.putString(Constants.SESSION_USER_NAME, userName);
			edit.putString(Constants.SESSION_USER_PASS, pwd);
			edit.commit();
		}
		//name
		/**
		 * 判断用户是否已经登录
		 */
		public static boolean isUserLogin(Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			String userName = ferences.getString(Constants.SESSION_USER_NAME,null);
			if(userName!=null && !"".equals(userName))
				return true;
			else
				return false;
			
		}
		public static String getUserName(Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			String userName = ferences.getString(Constants.SESSION_USER_NAME,null);
			if(userName!=null && !"".equals(userName))
				return userName;
			else
				return null;
		}
		//pwd
		public static String getPassword(Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			return ferences.getString(Constants.SESSION_USER_PASS,null); 
		}
		
		public static void setLoginStatus(boolean flgs,Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			Editor edit = ferences.edit();
			edit.putBoolean(Constants.LOGIN_STATUS, flgs); 
			edit.commit();
		}
		
		public static boolean getLoginStatus(Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			return ferences.getBoolean(Constants.LOGIN_STATUS, false); 
		}
		
		//sava key
		public static void setPreferences(String setKey,boolean flgs,Context context){
			SharedPreferences ferences = PreferenceManager.getDefaultSharedPreferences(context);
			Editor edit = ferences.edit();
			edit.putBoolean(setKey, flgs); 
			edit.commit();
		}
		public static boolean getPreferences(Context context,String setKey){
			SharedPreferences preference = context.getSharedPreferences("preference",Context.MODE_PRIVATE);
			return preference.getBoolean(setKey, false); 
		}
		
		//好友用户名
		public static void setFriendName(String friendname){
			CommonUtil.friendname = friendname;
		}
		//好友昵称
		public static void setFriendNick(String friendnick){
			CommonUtil.friendnick = friendnick;
		}
}